<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @open="handleOpen"
      @close="handleClose"
      destroy-on-close
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 基本信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单位名称" prop="name">
                  <el-input placeholder="单位名称" v-model="editForm.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="社会信用代码" prop="code">
                  <el-input placeholder="社会信用代码" v-model="editForm.code" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册资金" prop="regFund">
                  <el-input
                    placeholder="请输入注册资金"
                    v-model="editForm.regFund"
                    clearable
                    @input="fomateNumber(editForm, 'regFund', $event)"
                  >
                    <template #append>万元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位性质" prop="buyerType">
                  <CommonSelect
                    paramsName="甲方类别"
                    placeholder="单位性质"
                    v-model="editForm.buyerType"
                    valueKey="code"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位联系人" prop="contacts">
                  <el-input
                    placeholder="单位联系人"
                    v-model="editForm.contacts"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位电话" prop="telephone">
                  <el-input
                    placeholder="单位电话"
                    v-model="editForm.telephone"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="证书有效状态" prop="validType">
                  <CommonRadio
                    paramsName="证书有效状态"
                    v-model="editForm.validType"
                    valueKey="code"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="证书有效日期" prop="validDate">
                  <el-date-picker
                    v-model="editForm.validDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位所在省份" prop="province">
                  <CommonSelect
                    placeholder="单位所在省份"
                    :isFetch="false"
                    :dataList="provinceList.value"
                    v-model="editForm.province"
                    labelKey="valueColumn"
                    valueKey="codeColumn"
                    @change="provinceChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位所属地市" prop="city">
                  <CommonSelect
                    placeholder="单位所属地市"
                    :isFetch="false"
                    :dataList="cityList.value"
                    v-model="editForm.city"
                    labelKey="label"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位地址" prop="address">
                  <el-input placeholder="单位地址" v-model="editForm.address" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="营业执照附件" prop="licence">
                  <FileUpload :uploadUrl="uploadUrl" v-model="fileList" @change="fileChange" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收款人" prop="payee">
                  <el-input placeholder="收款人" v-model="editForm.payee" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankName">
                  <el-input placeholder="开户银行" v-model="editForm.bankName" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户账号" prop="bankAccount">
                  <el-input
                    placeholder="开户账号"
                    v-model="editForm.bankAccount"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="国别" prop="nationality">
                  <el-input
                    placeholder="请输入国别"
                    v-model="editForm.nationality"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否海外单位" prop="isOverseas">
                  <el-radio-group v-model="editForm.isOverseas">
                    <el-radio value="是">是</el-radio>
                    <el-radio value="否">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="note">
                  <el-input type="textarea" v-model="editForm.note" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { addRecords, editRecords, recordsDetail } from "@/api/project/yf/htgfdw";
import { ElMessage } from "element-plus";
import { assignObj, fomateNumber } from "@/utils/main";
import { phoneNumberReg } from "@/utils/validate";
import useCommonFetch from "@/hooks/useCommonFetch";
const dialogVisible = ref(false);
const editFormRef = ref();
const detailData = ref(null);
const uploadUrl = `/commonFile/uploadFile?modelName=合同供方单位`;
const fileList = ref([]);
const operateId = ref(null);
const provinceList = ref([]);
const cityList = ref([]);
const editForm = reactive({
  name: "",
  code: "",
  regFund: "",
  buyerType: "",
  contacts: "",
  telephone: "",
  validType: "",
  validDate: "",
  province: "",
  city: "",
  address: "",
  licence: "", //营业执照附件
  payee: "",
  bankName: "",
  bankAccount: "",
  nationality: "",
  isOverseas: "",
  note: "",
});
const rules = {
  name: [
    {
      required: true,
      message: "单位名称必填",
    },
  ],
  code: [
    {
      required: true,
      message: "社会信用代码必填",
    },
  ],
  regFund: [
    {
      required: true,
      message: "注册资金必填",
    },
  ],
  buyerType: [
    {
      required: true,
      message: "单位性质必填",
    },
  ],
  telephone: [
    {
      pattern: phoneNumberReg,
      message: "请输入正确的电话号码",
    },
  ],
  validDate: [
    {
      required: true,
      message: "证书有效日期必填",
    },
  ],
  province: [
    {
      required: true,
      message: "单位所在省份必填",
    },
  ],
  licence: [
    {
      required: true,
      message: "请上传营业执照附件",
    },
  ],
};
const title = computed(() => {
  return operateId.value ? "供方单位编辑" : "供方单位新增";
});
//获取数据详情
const getDetail = async () => {
  try {
    const res = await recordsDetail(operateId.value);
    detailData.value = res.data;
    fileList.value = res.data.fileList ? res.data.fileList : [];
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = () => {
  operateId.value = null;
  dialogVisible.value = true;
};
// 编辑
const edit = async (id) => {
  operateId.value = id;
  dialogVisible.value = true;
  await getDetail();
  nextTick(() => {
    assignObj(editForm, detailData.value);
    cityList.value = useCommonFetch("甲方所属地市", editForm.province);
  });
};
defineExpose({ add, edit });
//选择的省份改变
const provinceChange = () => {
  editForm.city = "";
  cityList.value = useCommonFetch("甲方所属地市", editForm.province);
};
const emit = defineEmits(["save-success"]);
//点击保存
const save = () => {
  try {
    editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let res;
        let params = {
          ...editForm,
        };
        if (operateId.value) {
          params.id = operateId.value;
          res = await editRecords(params);
        } else {
          res = await addRecords(params);
        }
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  }
};
//上传文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.licence = ids.join(",");
};
const handleOpen = () => {
  provinceList.value = useCommonFetch("甲方地区");
};
//关闭弹窗
const handleClose = () => {
  editFormRef.value.resetFields();
  fileList.value = [];
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
